"""
配置管理模块
支持从多种格式加载配置文件
"""

import os
import json
import logging
from typing import Dict, Any
from pathlib import Path

try:
    import yaml
    YAML_AVAILABLE = True
except ImportError:
    YAML_AVAILABLE = False

logger = logging.getLogger(__name__)

class ConfigLoader:
    """配置加载器"""
    
    def __init__(self, config_dir: str = None):
        if config_dir is None:
            config_dir = Path(__file__).parent
        self.config_dir = Path(config_dir)
        
    def load_json(self, filename: str) -> Dict[str, Any]:
        """加载JSON配置文件"""
        filepath = self.config_dir / filename
        try:
            with open(filepath, 'r', encoding='utf-8') as f:
                return json.load(f)
        except FileNotFoundError:
            logger.warning(f"配置文件 {filepath} 不存在")
            return {}
        except json.JSONDecodeError as e:
            logger.error(f"JSON配置文件 {filepath} 格式错误: {e}")
            return {}
            
    def load_yaml(self, filename: str) -> Dict[str, Any]:
        """加载YAML配置文件"""
        if not YAML_AVAILABLE:
            logger.warning("YAML模块未安装，跳过YAML文件加载")
            return {}
            
        filepath = self.config_dir / filename
        try:
            with open(filepath, 'r', encoding='utf-8') as f:
                return yaml.safe_load(f) or {}
        except FileNotFoundError:
            logger.warning(f"配置文件 {filepath} 不存在")
            return {}
        except yaml.YAMLError as e:
            logger.error(f"YAML配置文件 {filepath} 格式错误: {e}")
            return {}
            
    def merge_configs(self, *configs: Dict[str, Any]) -> Dict[str, Any]:
        """合并多个配置字典"""
        result = {}
        for config in configs:
            self._deep_merge(result, config)
        return result
        
    def _deep_merge(self, base: Dict[str, Any], override: Dict[str, Any]):
        """深度合并字典"""
        for key, value in override.items():
            if key in base and isinstance(base[key], dict) and isinstance(value, dict):
                self._deep_merge(base[key], value)
            else:
                base[key] = value

def load_config() -> Dict[str, Any]:
    """加载完整的系统配置"""
    loader = ConfigLoader()
    
    # 如果没有yaml模块，使用默认配置
    if not YAML_AVAILABLE:
        logger.info("使用默认配置")
        config = get_default_config()
    else:
        # 加载基础配置
        base_config = loader.load_yaml('config.yaml')
        
        # 加载环境特定配置
        env = os.getenv('IOT_ENV', 'development')
        env_config = loader.load_yaml(f'config_{env}.yaml')
        
        # 合并配置
        config = loader.merge_configs(get_default_config(), base_config, env_config)
    
    # 加载设备配置
    devices_config = loader.load_json('devices.json')
    if devices_config:
        config['devices'] = devices_config.get('devices', [])
    else:
        config['devices'] = []
        
    # 应用环境变量覆盖
    apply_env_overrides(config)
    
    return config

def apply_env_overrides(config: Dict[str, Any]):
    """应用环境变量覆盖配置"""
    # 数据库配置
    if 'IOT_DB_HOST' in os.environ:
        config.setdefault('storage', {}).setdefault('mysql', {})['host'] = os.environ['IOT_DB_HOST']
    if 'IOT_DB_PASSWORD' in os.environ:
        config.setdefault('storage', {}).setdefault('mysql', {})['password'] = os.environ['IOT_DB_PASSWORD']
        
    # InfluxDB配置
    if 'IOT_INFLUX_TOKEN' in os.environ:
        config.setdefault('storage', {}).setdefault('influxdb', {})['token'] = os.environ['IOT_INFLUX_TOKEN']
        
    # Web服务配置
    if 'IOT_WEB_PORT' in os.environ:
        config.setdefault('web', {})['port'] = int(os.environ['IOT_WEB_PORT'])
        
    # 日志级别
    if 'IOT_LOG_LEVEL' in os.environ:
        config.setdefault('logging', {})['level'] = os.environ['IOT_LOG_LEVEL']

def get_default_config() -> Dict[str, Any]:
    """获取默认配置"""
    return {
        "logging": {
            "level": "INFO",
            "format": "%(asctime)s - %(name)s - %(levelname)s - %(message)s",
            "file": "logs/iot_collector.log"
        },
        "engine": {
            "max_workers": 10,
            "collection_interval": 1.0,
            "connection_timeout": 30,
            "retry_attempts": 3,
            "buffer_size": 1000
        },
        "storage": {
            "sqlite": {
                "enabled": True,
                "path": "data/iot_collector.db",
                "cache_size": 10000
            },
            "influxdb": {
                "enabled": False,
                "url": "http://localhost:8086",
                "token": "",
                "org": "iot",
                "bucket": "iot_data"
            },
            "mysql": {
                "enabled": False,
                "host": "localhost",
                "port": 3306,
                "database": "iot_collector",
                "username": "iot",
                "password": ""
            }
        },
        "web": {
            "host": "0.0.0.0",
            "port": 5000,
            "debug": False,
            "secret_key": "your-secret-key-here"
        },
        "alarm": {
            "enabled": True,
            "notification": {
                "email": {
                    "enabled": False,
                    "smtp_server": "smtp.gmail.com",
                    "smtp_port": 587,
                    "username": "",
                    "password": "",
                    "recipients": []
                },
                "webhook": {
                    "enabled": False,
                    "url": "",
                    "headers": {}
                }
            }
        },
        "security": {
            "authentication": {
                "enabled": True,
                "default_username": "admin",
                "default_password": "admin123"
            },
            "ssl": {
                "enabled": False,
                "cert_file": "",
                "key_file": ""
            }
        }
    } 